package com.lik888.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lik888.entity.QxUser;
import com.lik888.entity.User;
import com.lik888.entity.UserLogin;
import com.lik888.mapper.QxUserMapper;
import com.lik888.mapper.UserMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class UserDetailsServiceImpl  implements UserDetailsService {
    private final StringRedisTemplate stringRedisTemplate;
    private final QxUserMapper qxUserMapper;
    ObjectMapper objectMapper = new ObjectMapper();
    private final UserMapper userMapper;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<User>();
        queryWrapper.eq(User::getUsername,username);
        User user = userMapper.selectOne(queryWrapper);
        if(user == null){
            throw new UsernameNotFoundException("用户不存在");
        }
        //判断密码是否正确
        List<String> list = new ArrayList<>();

        //TODO 从数据库中获取权限
        List<QxUser> qxUsers = qxUserMapper.selectList(new LambdaQueryWrapper<QxUser>().eq(QxUser::getUserid, user.getUserid()));
        //判断是否有权限
        if(qxUsers.isEmpty()){
            throw new RuntimeException("user has no permission");
        }
        //将权限转换为list
       list = qxUsers.stream().map(t->t.getPermission()).collect(Collectors.toList());

        UserLogin login = new UserLogin(user, list);
        return login;
    }
}
